package com.itheima.reggie.filter;


import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.R;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.User;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;


@WebFilter("/*")
public class LoginFilter implements Filter {
    @Value("${nologin.url}")
    private String urlPatterns;

    private AntPathMatcher antPathMatcher= new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        //登录相关的请求都应该放行
        String requestURI = httpServletRequest.getRequestURI();
        String[] patterns = urlPatterns.split(",");
        for (String pattern : patterns) {
            boolean match = antPathMatcher.match(pattern, requestURI);
            if (match){
                chain.doFilter(request,response);
                return;
            }
        }
        //判断用户是否登录，如果登录过了，放行
        //判断的依据
        Employee loginUser = (Employee) httpServletRequest.getSession().getAttribute("loginUser");
        if (loginUser != null){
            //此处获取登录用户的id，存入本地线程容器中
            UserHolder.set(loginUser.getId());
             chain.doFilter(request,response);//->aop-->controller-->service-->dao
            //释放
            UserHolder.remove();
             return;
        }
        User loginPone = (User) httpServletRequest.getSession().getAttribute("loginPhone");
        if (loginPone != null){
            //此处获取登录用户的id，存入本地线程容器中
            UserHolder.set(loginPone.getId());
            chain.doFilter(request,response);//->aop-->controller-->service-->dao
            //释放
            UserHolder.remove();
            return;
        }
        //如果没有登录，拦截
        //返回数据 R:code  0  data  不需要 msg
        R r = R.error("NOTLOGIN"); //{code:"0",msg:"NOTLOGIN",data:null}
        String jsonString = JSON.toJSONString(r);
        response.getWriter().write(jsonString);
    }

}
